package com.sl.plugin.step.object;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.sl.core.engine.meta.ProcessCompDescriptorService;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.meta.row.ProcessRowDescriptor;
import com.sl.core.engine.meta.valuemeta.ValueMetaArray;
import com.sl.core.engine.meta.valuemeta.ValueMetaObject;
import com.sl.core.engine.utils.BeanUtil;
import lombok.Getter;
import org.apache.commons.compress.utils.Lists;
import org.apache.hop.core.row.IValueMeta;
import org.apache.hop.pipeline.PipelineMeta;

import java.util.List;
import java.util.Map;

//@Comp(id = "ManyToOne", name = "多行转一行", desc = "多行转一行", groupName = "转换")
@Getter
public class ObjectMergeCompDescriptor extends AbstractProcessCompDescriptor<
        ObjectMergeComp, ObjectMergeCompContext> implements ProcessCompDescriptorService {


    @Override
    public void loadDescriptor(Map<String, Object> map) {

    }


    @Override
    public ProcessRowDescriptor getResultDescriptor(ProcessRowDescriptor rowDescriptor) {

        List<Map<String, Object>> listMapAttr = getListMapAttr("config.output");

        if (CollUtil.isEmpty(listMapAttr)) {
            return null;
        }
        ProcessRowDescriptor processRowDescriptor = new ProcessRowDescriptor();
        processRowDescriptor.setIsArray(false);
        processRowDescriptor.setBasicTypeFlag(false);

        List<IValueMeta> valueMetaList = Lists.newArrayList();
        CompConstructor compConstructor = this.getCompConstructor();
        PipelineMeta transMeta = compConstructor.getTransMeta();


        for (Map<String, Object> map : listMapAttr) {
            String fromTransformName = BeanUtil.getStr(map, "fromTransformName");
            String str = BeanUtil.getStr(map, "newFromTransformName");
            Boolean bool = BeanUtil.getBool(map, "outputDefine.isArrayFlag");

            ProcessRowDescriptor p = new ProcessRowDescriptor();
            p.toOutputDefine(BeanUtil.convert(transMeta), fromTransformName);
            if (StrUtil.isBlank(str)) {
                valueMetaList.addAll(p.getValueMetaList());
            } else {
                if(BooleanUtil.isTrue(bool)){
                    ValueMetaArray iValueMeta = new ValueMetaArray();
                    iValueMeta.setName(str);
                    iValueMeta.setFieldType(new ValueMetaObject());
                    iValueMeta.setFields(p.getValueMetaList());
                    valueMetaList.add(iValueMeta);
                }else{
                    ValueMetaObject iValueMeta = new ValueMetaObject();
                    iValueMeta.setName(str);
                    iValueMeta.setFields(p.getValueMetaList());
                    valueMetaList.add(iValueMeta);
                }

            }
        }

        processRowDescriptor.addValueMeta(valueMetaList);
        return processRowDescriptor;
    }
}
